import React from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  TextInput,
  Keyboard,
  Alert,
} from 'react-native';
import dismissKeyboard from 'dismissKeyboard';

import BasePage from '../common/BasePage';
import SizeUtils from '../../common/SizeUtils';
import ToastUtils from '../../common/ToastUtils';
import ResponseConstants from '../../common/ResponseConstants';
import Config from '../../config';
import Platform from 'Platform';
import HeartLoveSendAskQuestionAction from '../../actions/heart/HeartLoveSendAskQuestionAction';

export default class HeartLoveQuestionAskPage extends BasePage {
  constructor(props) {
    super(props);

    this.state.content = "";
    // this.state.content = `
    // import dismissKeyboard from 'dismissKeyboard';
    // import dismissKeyboard from 'dismissKeyboard';
    // import dismissKeyboard from 'dismissKeyboard';
    // import dismissKeyboard from 'dismissKeyboard';
    // import dismissKeyboard from 'dismissKeyboard';
    // import dismissKeyboard from 'dismissKeyboard';
    // import dismissKeyboard from 'dismissKeyboard';
    // import dismissKeyboard from 'dismissKeyboard';`;
    this.state.keyboardHeight = 0;
    this.state.statusText = "";
    this._textInput = null;
    this._currentY = 0;
    this._firstTime = true;
  }

  componentWillUpdate(nextProps, nextState) {
    if(nextState.statusText != this.state.statusText) {
      if(nextState.viewStatus == ResponseConstants.status_created_success) {
        Alert.alert('提示','发表成功',[
            {text:'确定',onPress:()=>{
              this.goBack();
              this._clearView();
            }}
          ])
      }
      else {
        ToastUtils.show(nextState.statusText);
        nextState.statusText = "";
      }
    }
  }

  componentDidMount() {
    // this._keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this._keyboardWillShow.bind(this));
    // this._keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
    // this._keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this._keyboardWillHide.bind(this));
    // this._keyboardDidChangeListener = Keyboard.addListener('keyboardDidChangeFrame', this._keyboardDidChange.bind(this));
    this._textInput.focus();
  }

  componentWillUnmount() {
    // this._keyboardWillShowListener.remove();
    // this._keyboardDidShowListener.remove();
    // this._keyboardWillHideListener.remove();
    // this._keyboardDidChangeListener.remove();

    this._textInput = null;
  }

  _dealLeavePage() {
    dismissKeyboard();
  }

  _dealEnterPage() {
    this._textInput.focus();
  }

  _clearView() {
    this.setState({
      contentheight:SizeUtils.translateDesignHeightToCode(200),
      content:"",
    });
    this._currentY = 0;
  }

  //none（默认值），拖拽时不隐藏软键盘。
  // on-drag 当拖拽开始的时候隐藏软键盘。
  // interactive 软键盘伴随拖拽操作同步地消失，并且如果往上滑动会恢复键盘。安卓设备上不支持这个选项，会表现的和none一样。
  render() {
    return(
      <View style={{}}>
        <ScrollView ref={(ref) => {this._scrollView = ref}}
            style={{width:SizeUtils.getWindowSize().width, height:SizeUtils.getWindowSize().height/2,
            backgroundColor:"#ffffff"}} keyboardShouldPersistTaps={"always"}
            showsVerticalScrollIndicator = {true}
            onScroll = {(event) => this._onScroll(event)}
            // keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
          >
          {this._renderInput()}
          {/* <View style={{width:SizeUtils.getWindowSize().width, height:this.state.keyboardHeight}}> */}
          {/* </View> */}
        </ScrollView>
        {this._renderNavigationBar()}
      </View>
    )
  }

  //keyboardType enum("default", 'numeric', 'email-address', "ascii-capable", 'numbers-and-punctuation', 'url', 'number-pad', 'phone-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search')
  _renderInput() {
    return(
      <View style={{
          paddingTop:Config.paddingTop, paddingLeft:SizeUtils.translateDesignWidthToCode(40),
          paddingRight:SizeUtils.translateDesignWidthToCode(40),}}>
        <TextInput
          style={{height: Math.max(SizeUtils.translateDesignHeightToCode(200), this.state.contentheight),
            borderColor: 'gray', borderWidth: 0,
            marginTop: SizeUtils.translateDesignHeightToCode(20),
             textAlignVertical: "top", fontSize: SizeUtils.translateFontSizeToCode(30)}}
          onChangeText = {(content) => this.setState({content})}
          placeholder = {"你的问题是什么呢"}
          multiline = {true}
          underlineColorAndroid="transparent"
          value = {this.state.content}
          onContentSizeChange={this._onContentSizeChange.bind(this)}
          maxLength={10000}
          underlineColorAndroid="transparent"
          // returnKeyType = "send"
          onSubmitEditing = {() => this._doSubmit()}
          // blurOnSubmit={true}
          enablesReturnKeyAutomatically={true}
          editable={!(this.props.pageData.routeData.editable === false)}
          keyboardType={"default"}
          ref = {(ref) => this._textInput = ref}
          // autoFocus = {true}
        />
      </View>
    )
  }

  _onScroll(event) {
    // console.log(event);
    this._currentY = event.nativeEvent.contentOffset.y
  }

  _onContentSizeChange(event) {
    this.setState({contentheight: event.nativeEvent.contentSize.height + SizeUtils.translateDesignHeightToCode(80)},
      () => {
        if(this.state.contentheight > SizeUtils.getWindowSize().height / 4) {
          this._scrollView.scrollTo(this._currentY + SizeUtils.translateDesignHeightToCode(40));
        }
      }
    );
  }

  _doSubmit() {
    new HeartLoveSendAskQuestionAction().call(this, {"content":this.state.content})
  }

  _onPressNavigationBarRightBtn() {
    this._doSubmit();
  }

  _keyboardWillShow(e){
      this._setKeyboradHeight(e.endCoordinates.height);
  }

  _keyboardDidShow(e) {
      this._setKeyboradHeight(e.endCoordinates.height, 1);
  }

  _keyboardWillHide(e){
      this._setKeyboradHeight(0);
  }

  _keyboardDidChange(e) {
    // ToastUtils.show("键盘高度改变:" + e.endCoordinates.height);
  }

  _setKeyboradHeight(height, duration = 250){
      this.setState({
          keyboardHeight:height
      }, ()=> {
        setTimeout(()=>{
          this._scrollView.scrollToEnd();
        },500);
      })
  }
}
